const shell = require('shelljs')
const path = require('path')
const os = require('os')

const { get, hasFile } = require('./common')
const { uniConfigLog } = require('./log')

let sleepTime = 0
const log = uniConfigLog

let CLI_PATH
let sysType = os.type()
if (sysType === 'Windows_NT') {
    CLI_PATH = 'cli'
} else {
    CLI_PATH = './cli'
}

log('环境', sysType, CLI_PATH)

const opens = {
    getPlatformInfo (platform, config, basePath, env) {
        const ideDir = get(config, `${platform}.ideDir`)
        const execCodeType = env === 'development' ? 'dev' : 'build'
        const projectDir = path.resolve(basePath, `./dist/${execCodeType}/${platform}`)
        return {
            ideDir,
            execCodeType,
            projectDir
        }
    },
    openReady ({ ideDir, projectDir, flagFile, remove } = {}) {
        opens.cancelOpen()
        if (remove) {
            // 如果是在编译之前打开编译器，删除project.config.json，监听该文件，如果存在则说明已经编译完成
            shell.rm('-f', path.resolve(projectDir, `./${flagFile}`))
        }

        async function hasOpenReally (resolve) {
            const isHasConfigJson = await hasFile(`./${flagFile}`, projectDir)

            if (isHasConfigJson) {
                setTimeout(() => {
                    resolve(true)
                }, 200)
            } else {
                sleepTime = setTimeout(() => {
                    hasOpenReally(resolve)
                }, 4000)
            }
        }

        return new Promise(resolve => {
            if (ideDir) {
                sleepTime = setTimeout(() => {
                    hasOpenReally(resolve)
                }, 2000)
            } else {
                if (!ideDir) {
                    log('当前调试器路径为空, 自动打开调试器功能将失效')
                }
                resolve(false)
            }
        })
    },
    cancelOpen () {
        clearTimeout(sleepTime)
    },
    async openWeixin (config, env, type, basePath, isBuildBefore = false) {
        opens.cancelOpen()
        // 微信项目源码路径
        const weixinDevtoolsPath = get(config, 'mp-weixin.ideDir')
        const EXEC_CODE_TYPE = env === 'development' ? 'dev' : 'build'
        const WEIXIN_PRESET_PATH = path.resolve(basePath, `./dist/${EXEC_CODE_TYPE}/${type}`)

        if (isBuildBefore) {
            // 如果是在编译之前打开编译器，删除project.config.json，监听该文件，如果存在则说明已经编译完成
            shell.rm('-f', path.resolve(WEIXIN_PRESET_PATH, './project.config.json'))
        }

        function isLogin () {
            return new Promise((resolve, reject) => {
                // TODO 暂不支持
                // shell.exec(`${CLI_PATH} islogin`, (code, err) => {
                //     console.log(99999)
                //     console.log(code, err)
                // })
                resolve(true)
            })
        }

        function openProject () {
            function exec (resolve) {
                // 打开小程序项目
                shell.exec(`${CLI_PATH} open --project ${WEIXIN_PRESET_PATH} --color=always`, (code, err) => {
                    if (resolve) {
                        resolve(code)
                    }

                    if (err && /登录/.test(err) && !/开发者/.test(err)) {
                        log('登录失效', '请扫描二维码登录开发者工具')
                        log('二维码准备中 ...')
                        shell.exec(`${CLI_PATH} login -f terminal --qr-size small`, (code, err) => {
                            exec(resolve)
                        })
                    }
                })
            }

            return new Promise((resolve) => {
                console.log('\n')
                log('正在打开小程序开发工具 ...')
                log('打开小程序项目 -> ' + WEIXIN_PRESET_PATH)
                setTimeout(() => {
                    exec(resolve)
                }, 3000)
            })
        }

        async function open (resolve) {
            shell.cd(weixinDevtoolsPath)
            await isLogin()
            await openProject()
            resolve()
        }

        async function hasOpenReally (resolve) {
            const isHasConfigJson = await hasFile('./project.config.json', WEIXIN_PRESET_PATH)

            if (isHasConfigJson) {
                setTimeout(() => {
                    open(resolve)
                }, 200)
            } else {
                sleepTime = setTimeout(() => {
                    hasOpenReally(resolve)
                }, 4000)
            }
        }

        return new Promise(resolve => {
            if (weixinDevtoolsPath) {
                sleepTime = setTimeout(() => {
                    hasOpenReally(resolve)
                }, 2000)
            } else {
                if (!weixinDevtoolsPath) {
                    log('当前调试器路径为空, 自动打开调试器功能将失效')
                }
                resolve()
            }
        })
    },

    openAlipay (config, env, platform, basePath, isBuildBefore = false) {
        const platformInfo = opens.getPlatformInfo(platform, config, basePath, env)
        opens.openReady ({
            ideDir: platformInfo.ideDir,
            projectDir: platformInfo.projectDir,
            flagFile: 'mini.project.json',
            remove: isBuildBefore
        })
            .then(res => {
                if (res === true) {
                    shell.exec(platformInfo.ideDir)
                }
            })
    }
}
module.exports = opens
